package middle

import (
	"commons/handler/response"
	"commons/record"
	"encoding/json"
	"imi/config"
	"reflect"
)

func Register(route config.Ctr) {

	class := route["class"]
	fun := route["func"].(string)
	auth := route["auth"].(bool)

	f := reflect.ValueOf(class)

	m2 := f.MethodByName("Init_")
	m2.Call(make([]reflect.Value, 0))

	if auth {
		m3 := f.MethodByName("Auth")
		res := m3.Call(make([]reflect.Value, 0))
		res1 := res[0]
		res2 := res[1]
		isBool, isOk := res1.Interface().(bool)
		if isOk && isBool {
			run(f, fun, class)
		} else {
			handle, isOk := res2.Interface().(response.Handle)
			if isOk {
				result, _ := json.Marshal(handle)
				response.Response.Write(result)
			}
		}

	} else {
		run(f, fun, class)
	}
}

func run(f reflect.Value, fun string, class interface{}) {
	m := f.MethodByName(fun)

	if m.Kind().String() == "invalid" {
		record.LogError(reflect.TypeOf(class).String() + " " + fun + "不存在 没有返回 response.Handle")
		return
	}
	res2 := m.Call(make([]reflect.Value, 0))

	if len(res2) > 0 {
		data := res2[0]
		handle, isOk := data.Interface().(response.Handle)
		if isOk {
			result, _ := json.Marshal(handle)
			response.Response.Write(result)
		}
		return
	}

}
